package com.example.spring_seatreservation.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.example.spring_seatreservation.Bean.R;
import com.example.spring_seatreservation.entity.Announcement;
import com.example.spring_seatreservation.mapper.AnnouncementMapper;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/announcement")
@AllArgsConstructor
public class AnnouncementController {

    private final AnnouncementMapper announcementMapper;

    @GetMapping("getAnnouncementList")
    public List<Announcement> getAnnouncementList(String libId){
        return announcementMapper.getAnnouncement(libId == null ? null : Long.parseLong(libId));
    }

    @GetMapping("getAnnouncementTop")
    public List<Announcement> getAnnouncementTop(){
        LambdaQueryWrapper<Announcement> lambdaQueryWrapper = Wrappers.<Announcement>lambdaQuery()
                .orderByDesc(Announcement::getCreateTime).last(" limit 5");
        return announcementMapper.selectList(lambdaQueryWrapper);
    }

    @PostMapping("submit")
    public Map<String, Object> submit(@RequestBody Announcement announcement){
        if (announcement.getId() == null) {
            announcementMapper.insert(announcement);
        } else {
            announcementMapper.updateById(announcement);
        }
        return new R().ok().builder();
    }

    @GetMapping("delete")
    public Map<String, Object> delete(Long id){
       announcementMapper.deleteById(id);
        return new R().ok().builder();
    }
}
